<script lang="ts" setup>
import { computed, defineEmits, ref, watch, h } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useVbenModal } from '@vben/common-ui';

import type { VxeGridProps, VxeGridListeners } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';

import {
  getRefundRecordDetailEditInfo,
  doRefundRecordAgainst,
  doRefundRecordApproval,
  doRefundRecordAdd,
  doRefundRecordEdit,
} from '#/api/refundRecord';

import {
  getDict,
  getAdminList,
  getSupplyList,
  getCompanyList,
} from '#/api/common';

import PurchaseBom from '../../modules/purchaseBom.vue';
import Warehouse from '../../modules/warehouse.vue';
import PurchaseModal from '../../modules/purchaseModal.vue';
import dayjs from 'dayjs';
import { AntPlusOutlined } from '@vben/icons';

import {
  Button,
  DatePicker,
  Input,
  message,
  Switch,
  Select,
  Divider,
  Spin,
} from 'ant-design-vue';

interface RowType {
  confirm_num?: number | string;
  price?: number | string;
  dead_line?: string;
  template_no?: string;
  material_use?: string;
  single_piece?: number | string;
  other_pay_remark?: string;
  remark?: string;
  material_id?: string;
  material_name?: string;
  material_sku_id?: number;
  unit?: string;
  action_num?: number;
  gift_num?: number;
  finish?: boolean;
  less_num?: number;
  total_price?: string;
  product_sn?: string;
  RefundRecord_bom_detail_id?: number;
  _X_ROW_KEY?: string;
}

const emit = defineEmits(['fetchData']);

const RecordId = ref<number>();
const routerData = ref<any>({});
const formData = ref<any>({});
const dict = ref<any>({});
const adminList = ref<any>([]);
const companyList = ref<any>([]);
const submitLoading = ref(false);

const isDisabled = ref(true);
const keyword = ref<Record<string, string>>({
  warehouse_id: '',
  supply_id: '',
});

const handleAgainstToApproval = async (type: string) => {
  try {
    if (type === 'approval') {
      await doRefundRecordApproval({ ids: [RecordId.value] });
    } else {
      await doRefundRecordAgainst({ ids: [RecordId.value] });
    }
    message.success('操作成功');
    emit('fetchData');
    modalApi.close();
  } catch (error) {}
};

const fetchData = async () => {
  const { row } = await getRefundRecordDetailEditInfo({
    record_id: RecordId.value,
  });
  formApi.setValues(row);
  formData.value = { ...row }; // 保留对旧逻辑的兼容

  Object.keys(keyword.value).forEach((key: string) => {
    if (row[key]) {
      keyword.value[key] = 'initValue:' + row[key];
    }
  });

  // 使用 setGridOptions 更新表格数据
  if (gridApi) {
    gridApi.setGridOptions({
      data: row.bom_list || [],
    });
  }
  // 初始化时根据结算方式设置结算规则的禁用状态
  updatePaymentRuleDisabledState();
};

const initClear = async () => {
  RecordId.value = 0;
  formData.value = {};
  if (gridApi) {
    gridApi.setGridOptions({
      data: [],
    });
  }
  Object.keys(keyword.value).forEach((key: string) => {
    keyword.value[key] = '';
  });
};
const init = async () => {
  const { select_list } = await getDict({
    keys: ['paymentMethod', 'paymentRule'],
    type: 2,
  });
  dict.value = select_list;

  const { list: adminApi } = await getAdminList({
    select: true,
    limit: 9999,
    group_id: 7,
  });
  adminList.value = adminApi;

  const companyApi = await getCompanyList({});
  companyList.value = companyApi;
};

// 当结算方式改变时，更新结算规则的禁用状态
const updatePaymentRuleDisabledState = () => {
  if (!dict.value.paymentRule || !formData.value.fk_type) return;

  dict.value.paymentRule.forEach((item: any) => {
    item.disabled = item.value !== formData.value.fk_type;
  });
};

// 监听结算方式变化
watch(
  () => formData.value.fk_type,
  () => {
    updatePaymentRuleDisabledState();

    // 如果当前选中的结算规则被禁用了，则清空结算规则的选择
    const currentRule = dict.value.paymentRule?.find(
      (item: any) => item.name === formData.value.fk_rule && item.disabled,
    );

    if (currentRule) {
      formData.value.fk_rule = undefined;
    }
  },
);

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } });
});

const handleClose = async () => {
  modalApi.close();
};

const [Modal, modalApi] = useVbenModal({
  class: 'w-5/6',
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>();
      initClear();
      init();
      if (routerData.value?.info?.record_id) {
        RecordId.value = routerData.value?.info?.record_id;
      }

      if (RecordId.value) {
        fetchData();
        disabledOn();
      } else {
        disabledOff();
      }
    }
  },
});

const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  cellStyle({ column }) {
    if (column.field === 'dead_line') {
      return {
        color: 'red',
      };
    }
  },
  columns: [
    { type: 'seq', width: 60, title: '序号' },
    { field: 'material_name', width: 200, title: '物料名称' },
    {
      field: 'action_num',
      width: 120,
      title: '数量',
      editRender: {},
      slots: { edit: 'actionNum' },
    },
    { field: 'stock', width: 100, title: '库存' },
    { field: 'unit', width: 100, title: '单位' },
    { field: 'price', width: 90, title: '单价' },
    { field: 'total_price', width: 100, title: '总价' },
    { field: 'unit_rate', width: 80, title: '换算比例' },
    { field: 'cloth_width', width: 80, title: '幅宽' },
    { field: 'gram_weight', width: 100, title: '克重' },
    {
      field: 'remark',
      title: '备注',
      editRender: {},
      slots: { edit: 'remark' },
    },
    {
      field: 'operation',
      width: 120,
      title: '操作',
      slots: { default: 'operation' },
    },
  ],
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
    showStatus: true,
  },
  height: '500px',
  keepSource: true,
  data: [],
  showOverflow: false,
};

const disabledOn = async () => {
  isDisabled.value = true;
  formApi.setState({ commonConfig: { disabled: true } });
};
const disabledOff = async () => {
  isDisabled.value = false;
  formApi.setState({ commonConfig: { disabled: false } });
};

const handleRowDelete = async (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getData();
    const index = currentData.findIndex(
      (item: any) => item._X_ROW_KEY === row._X_ROW_KEY,
    );
    if (index !== -1) {
      currentData.splice(index, 1);
      gridApi.setGridOptions({
        data: currentData,
      });
    }
  }
};

const opendAddSku = async () => {
  let saveData = await formApi.getValues();
  // console.log(saveData.purchase_id)
  if (!saveData.purchase_id) {
    message.warning('请选择采购单');
    return false;
  }
  SkuModalApi.setData({
    query: {
      in_stock: 1,
      purchase_id: saveData.purchase_id,
      ware_house_id: saveData.ware_house_id,
    },
    visibleFields: ['less_num'],
  }).open();
};

const shareData = (res: any) => {
  // console.log('shareData', res)
  if (res.shareType && res.shareType === 'warehouse') {
    doWarehouseList(res);
  } else if (res.shareType && res.shareType === 'purchase') {
    doPurchaseList(res);
  } else {
    doMaterialList(res);
  }
  return;
};

const doWarehouseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    const warehouse = res.list[0];
    formApi.setValues({
      ware_house_id: warehouse.id,
      out_ware_house_id: warehouse.code_name,
    });
  }
};

const doPurchaseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    const purchase = res.list[0];
    formApi.setValues({
      purchase_id: purchase.purchase_id,
      purchase_sn: purchase.purchase_sn,
      supply_id: purchase.supply_id,
      supply_name: purchase.supply_name,
    });
  }
};
const doMaterialList = (res: any) => {
  if (res.list && res.list.length > 0) {
    // 获取当前表格数据
    const currentTableData = gridApi.grid.getData() || [];

    // 将选中的物料数据转换为表格需要的格式
    const newRows = res.list.map((item: any) => ({
      purchase_bom_detail_id: item.purchase_bom_detail_id, // 物料ID
      material_sku_id: item.material_sku_id, // 物料skuID
      material_id: item.material_id, // 物料ID
      material_name: item.material_name, // 物料名称
      action_num: 0, // 数量
      price: item.price || 0, // 物料单价，默认为0
      total_price: item.price, // 总价
      unit: item.unit, // 单位
      unit_rate: item.unit_rate, // 换算比例
      stock: item.stock, // 库存
      cloth_width: item.cloth_width, // 幅宽
      gram_weight: item.gram_weight, // 克重
      remark: '', // 备注，默认为空
    }));

    // 合并现有数据和新数据
    const updatedTableData = [...currentTableData, ...newRows];

    // 更新表格数据
    gridApi.setGridOptions({
      data: updatedTableData,
    });
    message.success(`成功添加 ${res.list.length} 条物料`);
  } else {
    message.warning('未选择任何物料');
  }
};

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    submitLoading.value = true;
    try {
      let saveData = await formApi.getValues();
      if (gridApi) {
        const tableData = gridApi.grid.getData();
        saveData.bom_list = tableData;
      }
      if (RecordId.value) {
        await doRefundRecordEdit({ ...saveData, record_id: RecordId.value });
      } else {
        await doRefundRecordAdd(saveData);
      }
      message.success('保存成功');
      emit('fetchData');
      modalApi.close();
    } finally {
      submitLoading.value = false;
    }
  }
}
const handleSubmit = useDebounceFn(async () => {
  await onSubmit();
}, 300);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '收料单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'Input',
      fieldName: 'ware_house_id',
      label: '仓库ID',
      formItemClass: 'hidden',
    },
    {
      component: 'Input',
      fieldName: 'out_ware_house_id',
      label: '仓库',
      componentProps: () => ({
        onClick: (value: any) => {
          WarehouseApi.setData({
            query: { params: { type: '物料', is_stop: 0 } },
            selectType: 'radio',
          }).open();
        },
      }),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'purchase_sn',
      label: '采购单',
      componentProps: () => ({
        placeholder: '请选择采购单',
        onClick: (value: any) => {
          PurchaseModalApi.setData({ query: {}, selectType: 'radio' }).open();
        },
      }),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'purchase_id',
      label: '采购单ID',
      formItemClass: 'hidden',
    },
    {
      component: 'Input',
      fieldName: 'supply_name',
      label: '供应商(采购单)',
      disabled: true,
      componentProps: () => ({
        placeholder: '请选择采购单',
      }),
    },
    {
      component: 'Input',
      fieldName: 'supply_id',
      label: 'supply_id',
      formItemClass: 'hidden',
    },
    {
      component: 'DatePicker',
      fieldName: 'record_date',
      defaultValue: dayjs().format('YYYY-MM-DD'),
      label: '单据日期',
      componentProps: {
        class: 'w-full',
        type: 'date',
        clearable: true,
        placeholder: '请选择单据日期',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'product_sn',
      label: '生产单',
      componentProps: {
        placeholder: '请选择生产单',
      },
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: '备注',
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-6',
});

const gridEvents: VxeGridListeners<RowType> = {
  cellClick: ({ row }) => {
    // message.info(`cell-click: ${row.material_name}`);
  },
  editClosed: (res) => {
    if (res.column.field === 'action_num') {
      const row = res.row;
      const actionNum = Number(row.action_num) || 0;
      const price = Number(row.price) || 0;
      row.total_price = (actionNum * price).toFixed(2);
    }
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions,
});

const [SkuModal, SkuModalApi] = useVbenModal({
  connectedComponent: PurchaseBom,
});

const [WarehouseModal, WarehouseApi] = useVbenModal({
  connectedComponent: Warehouse,
});

const [PurchaseModalComp, PurchaseModalApi] = useVbenModal({
  connectedComponent: PurchaseModal,
});
</script>
<template>
  <Modal title="退料单">
    <div class="p-4">
      <Form />
      <Divider />
      <div class="mb-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">物料列表</h3>
        <Button :disabled="isDisabled" type="primary" @click="opendAddSku()">
          <AntPlusOutlined />
          新增物料
        </Button>
      </div>

      <Grid>
        <template #operation="{ row }">
          <Button
            :disabled="isDisabled"
            danger
            size="small"
            @click="handleRowDelete(row)"
            >删除</Button
          >
        </template>
        <template #actionNum="{ row }">
          <Input v-model:value="row.action_num" :disabled="isDisabled" />
        </template>
        <template #remark="{ row }">
          <Input v-model:value="row.remark" :disabled="isDisabled" />
        </template>
      </Grid>
    </div>
    <template #prepend-footer>
      <div>
        <Button @click="modalApi.close()">取消</Button>
      </div>
      <div class="space-x-2">
        <template v-if="RecordId && isDisabled">
          <Button
            type="ghost"
            class="bg-[#f56c6c] text-white hover:opacity-75"
            @click="
              handleAgainstToApproval(formData.posted ? 'against' : 'approval')
            "
          >
            {{ formData.posted ? '反审' : '审核' }}
          </Button>
          <Button
            type="ghost"
            v-if="!formData.posted"
            class="bg-[#f0a62f] text-[#fff] hover:opacity-75"
            @click="disabledOff()"
            >修改</Button
          >
        </template>
        <Button
          v-if="!isDisabled || !RecordId"
          type="primary"
          :loading="submitLoading"
          :disabled="submitLoading"
          @click="handleSubmit()"
          >保存</Button
        >
      </div>
    </template>

    <SkuModal @share-data="shareData" />
    <WarehouseModal @share-data="shareData" />
    <PurchaseModalComp @share-data="shareData" />
  </Modal>
</template>

<style lang="scss" scoped>
.fixed-width-select {
  width: 160px;
}
</style>
